package controller;

import myCode.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


/**
 * @pakager_name:controller
 * @description:
 * @author: 周铖鑫
 * @time: 2020/9/28 20:41
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {
    //代替数据库保存用户信息
    private static List<User> userList;

    public UserController() {
        super();
        userList = new ArrayList<>();
    }

    //响应 /register的GET请求
    @GetMapping(value = "/register")
    public String registerForm() {
        System.out.println("register GET方法被调用");
        return "registerForm";
    }

    @PostMapping(value = "/register")
    public String register(
            @RequestParam("loginname") String loginname,
            @RequestParam("password") String password,
            @RequestParam("username") String username,
            String request_locale,
            HttpServletRequest request,
            Model model) {
        System.out.println("register POST方法被调用");
        User user = new User();
        user.setLoginname(loginname);
        user.setPassword(password);
        user.setUsername(username);
        userList.add(user);
        model.addAttribute("user", user);
        return "loginForm";
    }

    @RequestMapping("/login")
    public String login(
            @RequestParam("loginname") String loginname,
            @RequestParam("password") String password,
            Model model
    ) {
        System.out.println("登录名:" + loginname + "密码:" + password);
        for (User user : userList) {
            if (user.getLoginname().equals(loginname)
                    && user.getPassword().equals(password)) {
                model.addAttribute("user", user);
                return "welcome";
            }
        }
        return "loginForm";
    }

}

